package com.atguigu.flink.chapter08;

import com.atguigu.flink.bean.LoginEvent;
import com.atguigu.flink.util.AtguiguUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/10/19 9:12
 */
public class Flink05_Project_High_Login {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        env
            .readTextFile("input/LoginLog.csv")
            //            .socketTextStream("hadoop162", 8888)
            .map(line -> {
                String[] data = line.split(",");
                return new LoginEvent(Long.valueOf(data[0]),
                                      data[1],
                                      data[2],
                                      Long.parseLong(data[3]) * 1000);
            })
            .keyBy(LoginEvent::getUserId)
            .countWindow(2, 1)
            .process(new ProcessWindowFunction<LoginEvent, String, Long, GlobalWindow>() {
                @Override
                public void process(Long key,
                                    Context ctx,
                                    Iterable<LoginEvent> elements,
                                    Collector<String> out) throws Exception {
                    List<LoginEvent> events = AtguiguUtil.toList(elements);
                    if (events.size() == 2) { // 如果长度是2才有需要进行计算
                        LoginEvent event1 = events.get(0);
                        LoginEvent event2 = events.get(1);
                        
                        String eventType1 = event1.getEventType();
                        String eventType2 = event2.getEventType();
                        
                        Long ts1 = event1.getEventTime();
                        Long ts2 = event2.getEventTime();
                        
                        if ("fail".equals(eventType1)
                            && "fail".equals(eventType2)
                            && Math.abs(ts1 - ts2) <= 2000) {
                            out.collect(key + " 在恶意登录, 请注意....");
                        }
                    }
                }
            })
            .print();
        
        env.execute();
    }
}
